<?php
/**
 * Created by PhpStorm.
 * User: zhd
 * Date: 2018/10/11
 * Time: 21:45
 */

namespace app\Module\Index\Controller;


use app\Lib\wechat\Code2Session;
use app\Lib\wechat\WXBizDataCrypt;
use app\Module\Index\Model\UserModel;

class LoginController
{
    /**
     * @param string $code
     * @param string $encryptedData
     * @param string $iv
     * @return string
     */
    public function indexAction($code, $encryptedData, $iv)
    {
        $code2Session         = new Code2Session();
        $code2Session->appid  = config('wechat')['appid'];
        $code2Session->secret = config('wechat')['secret'];
        $result               = $code2Session->jscode2session($code);
        $WXBizDataCrypt       = new WXBizDataCrypt($code2Session->appid, $result['session_key']);
        $error                = $WXBizDataCrypt->decryptData($encryptedData, $iv, $data);
        if ($error != 0) {
            return fail($error);
        }
        $userInfo  = json_decode($data, true);
        $userModel = new UserModel();
        if (empty($user = $userModel->getUser($userInfo['openId']))) {
            $userId = $userModel->addUser([
                'openid'          => $userInfo['openId'],
                'nickname'        => $userInfo['nickName'],
                'username'        => $userInfo['nickName'],
                'gender'          => $userInfo['gender'],
                'city'            => $userInfo['city'],
                'province'        => $userInfo['province'],
                'country'         => $userInfo['country'],
                'avatar_url'      => $userInfo['avatarUrl'],
                'last_login_ip'   => ip(),
                'last_login_time' => now(),
                'created'         => now(),
            ]);
        } else {
            $userId = $user['id'];
            $userModel->updateUser([
                'city'            => $userInfo['city'],
                'province'        => $userInfo['province'],
                'country'         => $userInfo['country'],
                'last_login_ip'   => ip(),
                'last_login_time' => now(),
            ], $userId);
        }
        session('openid', $userInfo['openId']);
        session('userId', $userId);
        return success(get_session_object()->getId());
    }
}